import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import Vant from "vant";
import "vant/lib/index.css";
import axios from "axios";
import { Toast } from "vant";

axios.defaults.baseURL = "http://127.0.0.1:3000";

// 添加请求拦截器设置token
axios.interceptors.request.use((config) => {
  if (localStorage.getItem("token") && !config.headers.Authorization) {
    config.headers.Authorization = "Bearer " + localStorage.getItem("token");
  }
  return config;
});
axios.interceptors.response.use((res) => {
  const { message } = res.data;
  if (message == "用户信息验证失败") {
    Toast.fail("用户信息验证失败");
    // 清除token和用户id, 跳回登录页
    localStorage.removeItem("userId");
    localStorage.removeItem("token");
    router.replace("/Login").catch(err => { });
  }
  return res;
});

// 路由守卫
router.beforeEach((to, from, next) => {
  if (to.meta.auth) {
    if (localStorage.getItem("token")) {
      next();
    } else {
      router.replace("/Login");
    }
  } else {
    next();
  }
});

Vue.prototype.$axios = axios;
// 添加全局属性保存背景图
Vue.prototype.$backgroundImg = {
  id: 1,
  url: require("@/assets/1.jpg"),
};
// 存储主题颜色
Vue.prototype.$colorObj = {
  id: 2,
  color: "#8d4bbb",
};

Vue.use(Vant);

// 将生产提示禁用
Vue.config.productionTip = false;

new Vue({
  router,
  render: function (h) {
    return h(App);
  },
}).$mount("#app");
